
package com.jf.cloud.delivery.controller.platform;

import com.jf.cloud.api.auth.constant.SysTypeEnum;
import com.jf.cloud.api.multishop.feign.ShopDetailFeignClient;
import com.jf.cloud.api.multishop.vo.ShopDetailVO;
import com.jf.cloud.api.platform.constant.OfflineHandleEventStatus;
import com.jf.cloud.api.platform.constant.OfflineHandleEventType;
import com.jf.cloud.api.platform.dto.OfflineHandleEventDTO;
import com.jf.cloud.api.platform.feign.OfflineHandleEventFeignClient;
import com.jf.cloud.api.platform.vo.OfflineHandleEventVO;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.delivery.dto.StationDTO;
import com.jf.cloud.delivery.model.Station;
import com.jf.cloud.delivery.service.StationService;
import com.jf.cloud.api.delivery.vo.StationVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 自提点信息
 *
 * @author zz
 * @date 2020-12-07 15:10:01
 */
@RestController("platformStationController")
@RequestMapping("/p/station")
@Tag( name = "[平台端]自提点信息")
public class StationController {
    private static final Logger logger = LoggerFactory.getLogger(StationController.class);

    @Autowired
    private OfflineHandleEventFeignClient offlineHandleEventFeignClient;
    @Autowired
    private ShopDetailFeignClient shopDetailFeignClient;
    @Autowired
    private StationService stationService;

    @GetMapping("/page")
    @Operation(summary = "获取自提点信息列表", description = "分页获取自提点信息列表")
    public ServerResponseEntity<PageVO<StationVO>> page(@Valid PageDTO pageDTO,@ParameterObject StationDTO stationDTO) {
        if (null != stationDTO.getShopName() && !stationDTO.getShopName().isEmpty()) {
            logger.info("根据店铺名称模糊查询店铺id");
            List<Long> shopIds = shopDetailFeignClient.getShopIdsByLikeShopName(stationDTO.getShopName()).getData();
            stationDTO.setShopIds(shopIds);
        }
        PageVO<StationVO> stationPage = stationService.pageStation(pageDTO, stationDTO);
        // 平台端需补充关联店铺名称
        List<StationVO> stations = stationPage.getList();
        if (!CollectionUtils.isEmpty(stations)) {
            Set<Long> shopIds = stations.stream().map(StationVO::getShopId).collect(Collectors.toSet());
            List<ShopDetailVO> shopDetails = shopDetailFeignClient.listByShopIds(new ArrayList<>(shopIds)).getData();
            if (!CollectionUtils.isEmpty(shopDetails)) {
                Map<Long, String> shopNameMap = shopDetails.stream().collect(Collectors.toMap(ShopDetailVO::getShopId, ShopDetailVO::getShopName));
                for (StationVO station : stations) {
                    station.setShopName(shopNameMap.get(station.getShopId()));
                }
            }
        }
        return ServerResponseEntity.success(stationPage);
    }

    @GetMapping
    @Operation(summary = "获取自提点信息", description = "根据stationId获取自提点信息")
    public ServerResponseEntity<StationVO> getByStationId(@RequestParam Long stationId) {
        StationVO stationVO = stationService.getByStationId(stationId);
        if (stationVO != null && stationVO.getStatus() == -1) {
            stationVO = null;
        }
        return ServerResponseEntity.success(stationVO);
    }

    @GetMapping("/get_offline_handle_event/{stationId}")
    @Operation(summary = "通过自提点id获取下线信息")
    @Parameter(name = "stationId", description = "自提点id", required = true)
    public ServerResponseEntity<OfflineHandleEventVO> getOfflineHandleEventByStationId(@PathVariable("stationId") Long stationId) {
        OfflineHandleEventVO offlineHandleEventVO = offlineHandleEventFeignClient.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.STATION.getValue(), stationId, null).getData();
        return ServerResponseEntity.success(offlineHandleEventVO);
    }

    @PostMapping("/offline")
    @Operation(summary = "下线自提点")
    public ServerResponseEntity<Void> offline(@RequestBody OfflineHandleEventDTO eventDTO) {
        this.isExist(eventDTO.getHandleId());
        // 新增下线信息
        eventDTO.setSysType(SysTypeEnum.STATION.value());
        eventDTO.setHandleType(OfflineHandleEventType.STATION.getValue());
        offlineHandleEventFeignClient.save(eventDTO);
        // 修改门店状态
        Station station = new Station();
        station.setStationId(eventDTO.getHandleId());
        station.setStatus(2);
        stationService.update(station);
        return ServerResponseEntity.success();
    }

    @PostMapping("/audit_station")
    @Operation(summary = "自提点下线审核")
    public ServerResponseEntity<Void> auditStation(@RequestBody OfflineHandleEventDTO eventDTO) {
        this.isExist(eventDTO.getHandleId());
        offlineHandleEventFeignClient.auditOfflineEvent(eventDTO);
        // 修改门店状态
        Station station = new Station();
        station.setStationId(eventDTO.getHandleId());
        if (OfflineHandleEventStatus.AGREE_BY_PLATFORM.getValue().equals(eventDTO.getStatus())) {
            station.setStatus(0);
        } else {
            station.setStatus(4);
        }
        stationService.update(station);
        return ServerResponseEntity.success();
    }

    /**
     * 检验门店是否存在
     * @param stationId 门店id
     */
    private void isExist(Long stationId) {
        StationVO stationVO = stationService.getByStationId(stationId);
        if (stationVO == null || stationVO.getStatus() == -1) {
            // 未找到该自提点信息
            throw new LuckException("未找到相应门店");
        }
    }
}
